﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.Web.Administration;
using PC.AzureMultiApp.Core.Helpers;
using System.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Net;

namespace PC.AzureMultiApp.Core
{
    public static class IISManager
    {

        public static void ConfigureIIS()
        {
            CreateNewSiteForDeployment();
            SetAppPoolAsLocalSystem();
        }

        private static void CreateNewSiteForDeployment()
        {
            try
            {
                var webApplicationProjectName = "Web";
                string appRoot = Path.Combine(Environment.GetEnvironmentVariable("RoleRoot") + @"\", @"approot" + @"\");
                string newWebsitePath = Path.Combine(appRoot, "DeploymentSite");

                if (!Directory.Exists(newWebsitePath))
                    Directory.CreateDirectory(newWebsitePath);

                using (ServerManager serverManager = new ServerManager())
                {
                    if (!serverManager.Sites.Where(s => s.Name.Equals("DeploymentSite", StringComparison.OrdinalIgnoreCase)).Any())
                    {
                        ApplicationPool applicationPool = serverManager.ApplicationPools.Add("DeploymentSitePool");
                        applicationPool.AutoStart = true;
                        applicationPool.ManagedPipelineMode = ManagedPipelineMode.Integrated;
                        applicationPool.ManagedRuntimeVersion = "v4.0";
                        applicationPool.ProcessModel.IdentityType = ProcessModelIdentityType.LocalSystem;

                        string binding = "*:80:";
                        int adminPort = 81;
                        if (serverManager.Sites[RoleEnvironment.CurrentRoleInstance.Id + "_" + webApplicationProjectName].Bindings.Where(b => b.EndPoint.Port == adminPort).Any())
                        {

                            binding = String.Format("{0}:80:",
                                serverManager.Sites[RoleEnvironment.CurrentRoleInstance.Id + "_" + "Web"].Bindings.Where(b => b.EndPoint.Port == adminPort).First().EndPoint.Address);
                        }


                        Site site = serverManager.Sites.Add("DeploymentSite", "http", binding, newWebsitePath);
                        site.Applications.First().ApplicationPoolName = "DeploymentSitePool";
                        site.ServerAutoStart = true;
                        serverManager.CommitChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message, "Error");
            }
        }


        private static void SetAppPoolAsLocalSystem()
        {
            var webApplicationProjectName = "Web";

            Trace.WriteLine("SetAppPoolAsLocalSystem", "Information");

            try
            {
                using (ServerManager serverManager = new ServerManager())
                {
                    string appPoolName = serverManager.Sites[RoleEnvironment.CurrentRoleInstance.Id + "_" + webApplicationProjectName].
                                                                                                        Applications.First().ApplicationPoolName;
                    var appPool = serverManager.ApplicationPools[appPoolName];
                    appPool.ProcessModel.IdentityType = ProcessModelIdentityType.LocalSystem;
                    serverManager.CommitChanges();
                }
                
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message, "Error");
            }
        }

    }
}
